extern crate alloc;

use api::gslb::{get_servers, select_server, PROTO_MQTT};
use clap::Parser;
use embed_std::{errorln, infoln};
use embed_std::thread::sleep_ms;
use sdk::api::api;
use sdk::util::copy_slice;
use sdk::SdkOptions;

/// IoT device emulator
#[derive(Parser)]
#[clap(name = "device-emu")]
#[clap(author = "Bo song <bo.song@epro.com.cn>")]
#[clap(version = "0.1.0")]
struct Args {
    /// 0(local) 1(local:249) 2(local:248) 3(huaweicloud) 4(AWS) 5(pet)
    #[clap(short, long, value_parser=clap::value_parser!(u8).range(0..45), default_value_t = 0)]
    region: u8,

    /// product code
    #[clap(short, long, value_parser, default_value_t=String::from("bsc001"))]
    product_code: String,

    /// device uid
    #[clap(short, long, value_parser, default_value_t=String::from("722AEB659D9D"))]
    device_uid: String,

    /// secret
    #[clap(short, long, value_parser, default_value_t=String::from("db4uz3yz16j95h3ykz2qffc6gp8xgz09"))]
    secret: String,

    /// secret
    #[clap(short, long, value_parser, default_value_t = false)]
    activate: bool,
}

const REGIONS: &[&str] = &[
    "127.0.0.1",
    "10.134.7.249",
    "10.134.7.248",
    "121.37.248.22",
    "52.34.146.19",
    // "112.74.164.75",
    "cn.api.iot.pesipet.com"
];

fn main() {
    let args = Args::parse();
    println!("region        : {}", args.region);
    println!("product_code  : {}", args.product_code);
    println!("device_uid    : {}", args.device_uid);
    println!("secret        : {}", args.secret);
    let param = sdk::PersisParams::get();
    copy_slice(args.product_code.as_bytes(), param.product_code.as_mut());
    copy_slice(args.device_uid.as_bytes(), param.device_uid.as_mut());
    copy_slice(args.secret.as_bytes(), param.secret.as_mut());

    let servers = get_servers(
        REGIONS[args.region as usize],
        param.product_code_str(),
        param.device_uid_str(),
    )
    .expect("get servers from gslb failed");
    infoln!("servers {:?}", servers);
    let sever = select_server(&servers, PROTO_MQTT).expect("no mqtt server found");
    let mut opts = SdkOptions::new();
    opts.ip = String::from(sever.addr());
    opts.do_activiate = args.activate;
    infoln!("region {} ip {}", args.region, opts.ip);
    sdk::rust_init_iot_sdk(opts);
    infoln!("do idle loop");
    loop {
        sleep_ms(5000);
        if let Some(api) = api() {
            _ = api.get_ota_version(3_000).map(|v|{
                infoln!("ota version: {:?}", v);
            }).map_err(|e|{
                errorln!("get ota version failed: {}", e);
            })
        }
    }
}
